import React, {useState, useEffect} from "react";
import PropTypes from "prop-types";
import {trim, map } from "lodash";
import Modal from "antd/lib/modal";
import Form from "antd/lib/form";
import Input from "antd/lib/input";
import InputNumber from "antd/lib/input-number";
import Select from "antd/lib/select";
import Radio from "antd/lib/radio";
import Checkbox from "antd/lib/checkbox";
import { wrap as wrapDialog, DialogPropType } from "@/components/DialogWrapper";
import DynamicComponent from "@/components/DynamicComponent";
import {policy} from "@/services/policy";
import { Dashboard } from "@/services/dashboard";
import { BarChartOutlined, TableOutlined, SolutionOutlined, ScheduleOutlined, TransactionOutlined, BlockOutlined, DatabaseOutlined } from '@ant-design/icons';

function CreateItemDialog({dialog, item}) {
  const [code, setCode] = useState("");
  const [title, setTitle] = useState("");
  const [icon, setIcon] = useState("");
  const [dashboard, setDashboard] = useState("");
  const [dashboardTitle, setDashboardTitle] = useState("");
  const [url, setUrl] = useState("");
  const [parameter, setParameter] = useState("");
  const [refreshRate, setRefreshRate] = useState(0);
  const [popHeight, setPopHeight] = useState("");
  const [isOpen, setIsOpen] = useState(false);
  const [isShortcut, setIsShortcut] = useState(false);
  
  const [isLoading, setIsLoading] = useState(false);
  const [isValid, setIsValid] = useState(false);
  const [saveInProgress, setSaveInProgress] = useState(false);
  const isCreateEnumsEnabled = policy.isAdmin();

  const [dashboardsAll, setDashboardsAll] = useState([]);

  useEffect(() => {
    if (Object.keys(item).length !== 0) {
      setCode(item.key);
      setTitle(item.label);
      setIcon(item.icon);
      setDashboardTitle(item.dashboardTitle);
      setDashboard(item.dashboard);
      setUrl(item.url);
      setParameter(item.parameter);
      setRefreshRate(item.refreshRate);
      setPopHeight(item.popheight);
      setIsOpen(item.isopen);
      setIsShortcut(item.isShortcut);
      setIsLoading(true);
    }

    Dashboard.publish()
    .then(results => {setDashboardsAll(results);})
    .catch(() => []);
  }, [item]);

  function handleCodeChange(event) {
    const value = event.target.value.replace(/[^0-9a-zA-z]/g, '');
    setCode(value);
    setIsValid(value !== "" && title !== "");
  }

  function handleTitleChange(event) {
    const value = trim(event.target.value);
    setTitle(value);
    setIsValid(value !== "" && code !== "");
  }

  function handleSubmit() {
    setSaveInProgress(true);
    dialog.close({
      key: code, 
      value: code, 
      title: code + ' ' + title, 
      label: title, 
      icon: icon, 
      dashboard: dashboard, 
      dashboardTitle: dashboardTitle,
      url: url, 
      parameter: parameter,
      refreshRate: refreshRate,
      popheight: popHeight,
      isopen: isOpen,
      isShortcut,
    });
  }

  if (Object.keys(item).length !== 0 && !isLoading) return null;

  return (
    <Modal
      {...dialog.props}
      {...(isCreateEnumsEnabled ? {} : { footer: null })}
      maskClosable = {false}
      title="菜单项"
      okText="保存"
      cancelText="取消"
      okButtonProps={{
        disabled: !isValid || saveInProgress,
        loading: saveInProgress,
        "data-test": "DashboardSaveButton",
      }}
      cancelButtonProps={{
        disabled: saveInProgress,
      }}
      onOk={handleSubmit}
      closable={!saveInProgress}
      wrapProps={{
        "data-test": "CreateDashboardDialog",
      }}>
      <DynamicComponent name="CreateItemDialogExtra" disabled={!isCreateEnumsEnabled}>
      <Form>
        <Form.Item label="编码">
          <Input
            defaultValue={code}
            onChange={handleCodeChange}
            placeholder="编码"
            disabled={saveInProgress || Object.keys(item).length !== 0}
            autoFocus
          />
        </Form.Item>
        <Form.Item label="名称">
          <Input
            defaultValue={title}
            onChange={handleTitleChange}
            placeholder="名称"
            disabled={saveInProgress}
          />
        </Form.Item>
        <Form.Item label="图标">
          <Input style={{ width: '200px' }} 
            value={icon}
            onChange={e => setIcon(e.target.value)}
            placeholder="图标"
          />
          <a href="https://ant.design/components/icon-cn/" rel="noopener noreferrer" target="_blank">AntD_V4图标代码</a>如：FileDoneOutlined
          <br/>
          <Radio.Group size="small" style={{ marginTop: 16 }}
            onChange={e => setIcon(e.target.value)}
          >
            <Radio.Button key="BarChartOutlined" value="BarChartOutlined"><BarChartOutlined /></Radio.Button>
            <Radio.Button key="TableOutlined" value="TableOutlined"><TableOutlined /></Radio.Button>
            <Radio.Button key="SolutionOutlined" value="SolutionOutlined"><SolutionOutlined /></Radio.Button>
            <Radio.Button key="ScheduleOutlined" value="ScheduleOutlined"><ScheduleOutlined /></Radio.Button>
            <Radio.Button key="TransactionOutlined" value="TransactionOutlined"><TransactionOutlined /></Radio.Button>
            <Radio.Button key="BlockOutlined" value="BlockOutlined"><BlockOutlined /></Radio.Button>
            <Radio.Button key="DatabaseOutlined" value="DatabaseOutlined"><DatabaseOutlined /></Radio.Button>
          </Radio.Group> 
          <Checkbox
            name="is_open"
            checked={isOpen}
            onChange={e => setIsOpen(e.target.checked)}>
            菜单项默认展开
          </Checkbox>
          <Checkbox
            name="is_shortcut"
            checked={isShortcut}
            onChange={e => setIsShortcut(e.target.checked)}>
            桌面快捷方式
          </Checkbox>
        </Form.Item>
        <Form.Item label="链接类型">
          <div>
            报表：
            <Select style={{ width: 200 }} 
              defaultValue={dashboard}
              onChange={value => setDashboard(value)}
            >
            <option value=''>--无--</option>
            <option value='URL'>[外部链接：新窗口]</option>
            <option value='POP'>[外部链接：弹出窗]</option>
            {map(dashboardsAll, item => (
              <option value={item.id}>{item.name}</option>
            ))}
            </Select>
          </div>  
        </Form.Item>
        <Form.Item label="报表" hidden={dashboard==="" ? true : false}>
          <div>
            <br/>
            报表弹窗标题：
            <Input type="text" style={{width:300}}
              defaultValue={dashboardTitle}
              onChange={e => setDashboardTitle(e.target.value)}
            />
          </div>
          <div>
            <br/>
            自动刷新频率：
            <InputNumber type="text" style={{width:80}}
              defaultValue={refreshRate}
              onChange={value => setRefreshRate(value)}
            />
            (单位：秒；0不刷新，最小值5秒)
          </div>  
          <div>
            <br/>
            外部链接地址：
            <Input type="text" style={{width:300}}
              defaultValue={url}
              onChange={e => setUrl(e.target.value)}
            />
          </div>
          <div>
            <br/>
             窗口报表参数：
            <Input type="text" style={{width:300}}
              defaultValue={parameter}
              onChange={e => setParameter(e.target.value)}
            />
            (报表参数例：p_参数名=参数值；<br/>外链弹窗宽度例：80% 新窗口例：width=200,height=100,location=no)
          </div>  
          <div>
            <br/>
            弹窗内容高度
            <Input type="text" style={{width:100}}
              value={popHeight}
              onChange={e => setPopHeight(e.target.value)}
            />
            (例：480px)
          </div>  
        </Form.Item>
      </Form>
      </DynamicComponent>
    </Modal>
  );
}

CreateItemDialog.propTypes = {
  dialog: DialogPropType.isRequired,
  item: PropTypes.object,
};

CreateItemDialog.defaultProps = {
  item: {},
};

export default wrapDialog(CreateItemDialog);
